﻿using Autofac;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Warehouse.Entites;
using Warehouse.IServices;
using Warehouse.IServices.Conveyorlines;
using Warehouse.IServices.TESinterface;
using Warehouse.Services.Conveyorlines;
using Warehouse.Services.Repository;
using Warehouse.ViewModels;
using Warehouse.ViewModels.TESinterfaceDTO;
using WCS.Entities;
using WCS.Entities.BulkStorage;
using WCS.IServices;
using WCS.Services;
using WCS.ViewModels;

namespace Warehouse.Services
{
    public class StorageServices : Repository<Storage>, IStorageServices
    {
        private readonly Repository<Storage> _storage;
        private readonly Repository<Material> ware;
        private readonly IDeviceManager _deviceManager;
        private readonly ILogger<StorageServices> logger;
        private readonly ILifetimeScope lifetimeScope;
        private readonly IConveyorIServices conveyorIServices;
        private readonly IPsCarServices psc;


        public StorageServices(Repository<Storage> storage, Repository<Material> ware, ILogger<StorageServices> logger, ILifetimeScope lifetimeScope, IDeviceManager _deviceManager, IConveyorIServices conveyorIServices, IPsCarServices psc)
        {
            _storage = storage;
            this.ware = ware;
            this.logger = logger;
            this.lifetimeScope = lifetimeScope;
            this._deviceManager = _deviceManager;
            this.conveyorIServices = conveyorIServices;
            this.psc = psc;
        }

        //显示+查询
        public dynamic StorageShow(string StorageNumber)
        {
            //var list=_storage.Query();
            var list = from x in _storage.Query()
                       select new
                       {
                           x.StorageNumber,
                           x.Type,
                           x.MaterialName,
                           x.WHNumber,
                           x.QRcodeId,
                           x.EnterTime,
                           x.Normal,
                           x.Remark
                       };
            if (!string.IsNullOrEmpty(StorageNumber))
            {
                list = list.Where(x => x.StorageNumber == StorageNumber).ToList();
            }
            return 1;
            //return new
            //{
            //    Rcount = list.Count(),
            //    Plist = list.OrderBy(x => x.StorageNumber).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList(),
            //};
        }

        //添加
        public async Task<List<Storage>> StorageAdd(Storage model)
        {

            var list = _storage.Query();
            _storage.Add(model);
            return list;
        }

        ////移库
        //public List<Storage> StorageUpdate(string storageNumber)
        //{
        //    var list=_storage.Query();
        //    var sty = list.Where(x => x.StorageNumber == storageNumber).First();
        //    var lists = ware.Query();
        //    var bit = lists.Where(x => x.WHStare == false).First();
        //    warehouseServices.UpdateWare(sty.WHNumber);
        //    sty.WHNumber=bit.WHNumber;
        //    _storage.Update(sty);
        //    warehouseServices.UpdateWare(sty.WHNumber);
        //    return list;
        //}

        public async Task<bool> PutStorage()
        {
            var isOk = false;
            var numbell = new UniqueNumberGenerator();
            var time = Convert.ToInt32(DateTime.Now.ToString("ddHHss"));
            try
            {
                using var db = lifetimeScope.BeginLifetimeScope().Resolve<ISqlSugarClient>().CopyNew();
                var list = TcpClientReadCode.CodeMessage;
                var selectedMessageInfo = string.Empty;

                foreach (var item in list)
                {
                    if (item.Value != null && item.Value.Contains("24"))
                    {
                        selectedMessageInfo = item.Value;
                        break; // 假设只需要第一个匹配项  
                    }
                }


                for (int i = 0; i <= 3; i++)
                {
                    if (!string.IsNullOrEmpty(selectedMessageInfo))
                    {
                        var a = _deviceManager.Ports.FirstOrDefault(i => i.DeviceId == "11001");
                        var res = a?.BelongDevice.Operation.ReadInt16("730");
                        if (res != null && res.Value == 1)
                        {
                            a?.BelongDevice.Operation.Write("732", (short)21001);
                            a?.BelongDevice.Operation.Write("734", (short)time);
                        }
                    }
                }

                //确保长度足够 
                if (!string.IsNullOrEmpty(selectedMessageInfo) && selectedMessageInfo.Contains("24"))
                {
                    var boxmodel = new BOX
                    {
                        Id = DateTime.Now.ToString("yyyyMMddHHmmss"),
                        MaterialNumber = numbell.GenerateUniqueNumber(),
                        MaterialName = "",
                        MaterialColor = selectedMessageInfo.Substring(42, 2),
                        MaterialGrade = selectedMessageInfo.Substring(31, 1),
                        MaterialVoltage = "",
                        MaterialEfficiency = selectedMessageInfo.Substring(32, 4),
                        MaterTime = selectedMessageInfo.Substring(1, 6),
                        MaterAum = selectedMessageInfo.Substring(27, 4) // ... (构建BOX对象，确保Substring调用不会越界)  
                    };

                    var boxes = new List<string>();

                    var bulkStorage = new BulkStorage
                    {
                        Id = boxmodel.Id,
                        MaterialNumber = boxmodel.MaterialNumber,
                        MaterialName = boxmodel.MaterialName,
                        MaterialColor = boxmodel.MaterialColor,
                        MaterialGrade = boxmodel.MaterialGrade,
                        MaterialVoltage = boxmodel.MaterialVoltage,
                        MaterialEfficiency = boxmodel.MaterialEfficiency,
                        MaterialPutPort = "EAEX2",
                        MaterialOutPort = "EAEX1",
                        MaterialPort = "EA",
                    };
                    if (!boxes.Contains(bulkStorage.MaterialNumber))
                    {
                        boxes.Add(bulkStorage.MaterialNumber);
                    }

                    if (bulkStorage != null)
                    {
                        string li = conveyorIServices.BulkPutStorage(bulkStorage);
                        if (!string.IsNullOrEmpty(li))
                        {
                            if (boxes.Contains(li))
                            {
                                boxes.Remove(li);
                            }
                        }
                    }

                    var count = await db.Insertable<BOX>(boxmodel).ExecuteCommandAsync();
                    isOk = count > 0;

                    logger.LogInformation("Data inserted successfully.");
                }

            }
            catch (Exception ex)
            {
                logger.LogError($"Error inserting data: {ex.Message}");
            }

            return isOk;
        }

        public class UniqueNumberGenerator
        {
            private string prefix = "JW";
            public string GenerateUniqueNumber()
            { /*使用当前时间的年月日时分秒毫秒作为编号的后半部分  注意：这里使用了毫秒来增加精度，但你也可以根据需要调整（如使用微秒等）*/
                string timePart = DateTime.Now.ToString("yyyyMMddHHmmss"); // 将前缀和时间部分拼接起来形成完整的编号
                return timePart + prefix;
            }
            public string GenerateNumber()
            { /*使用当前时间的年月日时分秒毫秒作为编号的后半部分  注意：这里使用了毫秒来增加精度，但你也可以根据需要调整（如使用微秒等）*/
                string timePart = DateTime.Now.ToString("ddHHss"); // 将前缀和时间部分拼接起来形成完整的编号
                return timePart;
            }
        }

        //出库
        public async Task<bool> OutStorage(OutStorageModel outStorage)
        {
            try
            {
                var Tesout = ware.Query().Where(x => x.MaterialNumber == outStorage.MaterialNumber).FirstOrDefault();
                if (Tesout != null)
                {
                    
					if (outStorage.location == "A")
					{
						var Tes = new DispatchHandlingDTO()
						{
							warehouseID = "HETU",
							requestID = "86f3ebf3-1ba4-4ccc1",
							clientCode = "WCS",
							desType = 5,
							srcType = 1,
							podID = outStorage.storageId,
							priority = 3,
							bizID = DateTime.Now.ToString("ddHHmmss"),
							desExt = new Dictionary<string, int>()
						{
							{ "unload", 1 }
						},
							bizExt = new Dictionary<string, string>()
						{
							{ "bizType", "out" }
						},
							desStationCodes = "A1054",
						};
                        psc.newMovePodTasks(Tes);
					}
					else
					{
						var Tes = new DispatchHandlingDTO()
						{
							warehouseID = "HETU",
							requestID = "86f3ebf3-1ba4-4ccc1",
							clientCode = "WCS",
							desType = 5,
							srcType = 1,
							podID = outStorage.storageId,
							priority = 3,
							bizID = DateTime.Now.ToString("ddHHmmss"),
							desExt = new Dictionary<string, int>()
						{
							{ "unload", 1 }
						},
							bizExt = new Dictionary<string, string>()
						{
							{ "bizType", "out" }
						},
							desStationCodes = "A1057",
						};
                        psc.newMovePodTasks(Tes);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"出库失败，失败信息：{ex.Message}");
            }
            return true;
        }
    }
}
